﻿"use strict"
define(['admin/app', "service/admin/productService", "ui.sortable", "angular-kindeditor", "ui.file.manage"], function (app) {

    app.controller("productController", function ($scope, $state, $stateParams, $uibModal, $q, utils, w5cValidator, baseService, productService) {
        $scope.psdisabled = false;
        $scope.sel_sku_info = [];
        $scope.list = {};
        $scope.goods_service_items = []
        $scope.shop_service_items = [];
        $scope.query = {
            page: 1, size: 20, sort: 1, keyword: '', sell_out: 0,  sale_status: 0, audit_status: 0
        };
        $scope.out_rate = 0;
        $scope.editConfig = {
            autoHeightMode: true,
            items: ['source', 'preview', '|', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', '|', 'emoticons', 'image', 'multiimage', 'link']
        };
        $.extend($scope.query, $stateParams);
        var methods = {
            //查询以及获取全部数据
            search: function () {
                productService.gets($scope.query).success(function (response) {
                    $scope.list = response.data;
                });
            },
            //获取所有分类
            get_categorys: function () {
                productService.get_token_categorys().success(function (response) {
                    $scope.model.token_categorys = response.data.name;
                });
            },
            //获取分类
            get_category: function (id) {
                productService.get_categorys({ id: id }).success(function (response) {
                    $scope.model.category = response.data.name;
                });
            },
            //获取规格
            get_sku_info: function (id) {
                productService.get_sku_info({ merchant_id: 6 }).then(function (response) {
                    $scope.sel_sku_infos = response.data;
                });
            },
            //编辑
            edit: function () {
                Library('ui.sortable');
                Library('ngKeditor');
                if ($stateParams.action == 'edit' && $stateParams.id > 0) {
                    $q.all([productService.get({
                        id: $stateParams.id
                    })]).then(function (response) {
                        $scope.model = response[0].data.data;
                        methods.get_sku_info($scope.model.merchant_id);
                        methods.get_category($scope.model.category_id);
                        $scope.model.type = response[0].data.data.type.toString();;
                        $.each($scope.model.sku_infos, function (index, item) {
                            //var result = $.grep($scope.sel_sku_infos, function (n, i) {
                            //    return n.id == item.id;
                            //});
                            //if (result.length > 0) 
                            $scope.sel_sku_info.push(item);
                        });
                        methods.change_sku();
                    });
                    $scope.breadcrumb = '详情';
                } else if ($stateParams.action == 'audit' && $stateParams.id > 0) {
                    productService.get({
                        id: $stateParams.id
                    }).success(function (response) {
                        $scope.model = response.data;
                        //if (response.data.audit_status == 1)
                        //    $scope.model.audit_status = "";
                        $scope.model.audit_status = response.data.audit_status.toString();
                    });

                    $scope.breadcrumb = '审核';
                }else {
                    methods.get_sku_info();
                    $scope.model = {
                        id: 0,
                        product_type: 1,
                        sale_status: 0,
                        stock: 0,
                        unit_qty: 1,
                        measure_unit: 1,
                        service_items: [],
                        shop_category_ids: [],
                        image_path: [],
                        sku_infos: [],
                        product_skus: [],
                        product_member_settings: [],
                        props: [],
                        type: "1",
                        sale_count: 0
                    };
                    $scope.breadcrumb = '新增';
                }
                w5cValidator.setRules({
                    code: {
                        required: '请填写商品编号'
                    },
                    name: {
                        required: '请填写商品标题'
                    },
                    short_description: {
                        required: '请填写商品描述'
                    },
                    price: {
                        required: '请填写价格',
                        pattern: '请填写正确的价格，如￥99'
                    },
                    stock: {
                        required: '请填写总库存',
                        pattern: '请填写正确的总库存，如100'
                    },
                    unit_qty: {
                        required: '请填写重量/数量',
                        pattern: '请填写正确的重量/数量，如1'
                    },
                    measure_unit: {
                        required: '请选择单位'
                    },
                    file: {
                        required: '请必须添加一张图片'
                    }
                });
            },
            //保存商品
            save: function () {
                var model = $scope.model;
                $scope.psdisabled = true;
                productService.save(model).success(function (response) {
                    utils.notify(response.result_msg, response.result_code == 1000 ? "success" : "warning");
                    $scope.psdisabled = false;
                    if (response.result_code == 1000) {
                        methods.goBack();
                    }
                });
            },
            search_page: function (page) {
                $scope.query.page = page;
                methods.search('page', $scope.query.page);
            },
            change_sku: function () {
                $scope.skuTitles = [], $scope.skuItems = [], $scope.skuColumn = [];
                var columnIndex = 0;
                $.each($scope.sel_sku_info, function (i, item) {
                    if ($scope.model.sku_infos[i].sku_values.length > 0) {
                        $scope.skuColumn.push(columnIndex);
                        $scope.skuTitles.push(item.name);
                        $scope.skuItems.push($scope.model.sku_infos[i].sku_values);
                        columnIndex++;
                    }
                });
                $scope.$broadcast('sku:change');
            },
            sku_chooses_del: function (key) {
                $scope.sel_sku_info.splice(key, 1);
                $scope.model.sku_infos.splice(key, 1);
                methods.change_sku();
            },
            sel_sku_info_change: function (selected, model_selected) {
                var has = $.grep($scope.sel_sku_info, function (n, i) {
                    return n.id == selected.id;
                }).length > 0;
                if (has) utils.notify(selected.name + '已经选择，规格不可以相同', "warning");
                else {
                    $scope.sel_sku_info.push(selected);
                    $scope.model.sku_infos.push({
                        id: selected.id,
                        name: selected.name,
                        shop_id: selected.shop_id,
                        sku_values: []
                    });
                }
            },
            sel_sku_value_change: function (sku_info, sel_sku_value) {
                var sku_valueed = methods.is_sku_valueed(sku_info, sel_sku_value);
                if (!sku_valueed) sku_info.sku_values.push(sel_sku_value);
                else sku_info.sku_values.splice($.inArray(sku_valueed, sku_info.sku_values), 1);
                methods.change_sku();
            },
            is_sku_valueed: function (sku_info, sel_sku_value) {
                var result = $.grep(sku_info.sku_values, function (n, i) {
                    return n.id == sel_sku_value.id;
                });
                return result.length > 0 ? result[0] : undefined;
            },
            goBack: function () {
                if ($stateParams.action == 'add') $state.go('app.product.list');
                else history.back();
            },
            disable: function (id) {
                productService.disable(id)
                    .success(function (response) {
                        utils.notify(response.result_msg, response.result_code == 1000 ? "success" : "warning");
                        if (response.result_code == 1000) {
                            methods.search();
                        }
                    })
            },
            remove: function (model) {
                var modal = utils.confirm({
                    msg: "是否需要删除当前项目",
                    ok: "确定",
                    cancel: "取消"
                });
                modal.result.then(function () {
                    productService.delete(model.id).success(function (response) {
                        utils.notify(response.result_msg, response.result_code == 1000 ? "success" : "warning");
                        if (response.result_code == 1000) utils.remove($scope.model, model);
                    })
                })
            },
            set_stock: function () {
                if ($scope.model.product_skus.length > 0) {
                    $scope.model.stock = 0;
                    $.each($scope.model.product_skus, function (i, item) {
                        if (item.stock) $scope.model.stock += item.stock;
                    });
                }
            },
            delete_image: function (file_url) {
                var index = $scope.model.image_path.indexOf(file_url);
                $scope.model.image_path.splice(index, 1);
            },
            fallback: function () {
                utils.notify("复制成功", "success");
            },
            add_product_property: function () {
                $scope.model.props.push({
                    id: 0
                });
            },
            del_product_property: function (key) {
                $scope.model.props.splice(key, 1);
            },
            audit: function () {
                let audit_model = {
                    id: $scope.model.id,
                    audit_status: $scope.model.audit_status,
                    audit_reason: $scope.model.audit_reason
                };
                productService.audit(audit_model)
                    .success(function (response) {
                        utils.notify(response.result_msg, response.result_code == 1000 ? "success" : "warning");
                        if (response.result_code == 1000) {
                            methods.search();
                        }

                    })
            },
            open_category: function (model) {
                $uibModal.open({
                    templateUrl: 'category.html',
                    controller: 'category_ctrl',
                    resolve: {
                        model: function () {
                            return model;
                        }
                    }
                }).result.then(function (model) {
                    methods.search();
                });
            },
        }
       
        angular.extend($scope, methods);
        if ($state.includes('app.product.detail') || $state.includes('app.product.audit_detail')) {
            methods.edit();
            //methods.get_category();
        } else {
            methods.search();
        }
    });
    app.controller('category_ctrl', function ($scope, $uibModalInstance, utils, productService, model) {
        $scope.model = model;
        $scope.error = {};
       
        productService.get_token_categorys().success(function (response) {
            $scope.model.token_categorys = response.data;
        });
        productService.get_categorys({ id: $scope.model.category_id }).success(function (response) {
            $scope.model.category_f = response.data.name;
        });
        $scope.c = function () {
                  $scope.error.f_c = false;
                  $scope.error.s_c = false;
                  $scope.selected2 = "";
        };
        $scope.editCategory = function () {
            $scope.error.f_c  = $scope.selected ? false : true;
            $scope.error.s_c = $scope.selected2 ? false : true;
            if ($scope.error.f_c == true) {
                utils.notify("请选择第一级分类");
                return;
            }
            if ($scope.error.s_c == true) {
                utils.notify("请选择第二级分类");
                return;
            }
            $scope.psdisabled = true;
            productService.editProductCategory($scope.model.id,$scope.selected2.id).success(function (response) {
                utils.notify(response.result_msg, response.result_code == 1000 ? "success" : "warning");
                if (response.result_code == 1000)
                    $uibModalInstance.close($scope.model);
                else
                    $scope.psdisabled = false;
            }).error(function () { $scope.psdisabled = false; });
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };
    });
    app.directive("uiProductSku", function ($compile) {
        return {
            restrict: 'EA',
            replace: true,
            link: function (scope, element, attrs) {
                //开始创建Table表
                scope.creatTable = function () {
                    if (!scope.skuTitles) return;
                    scope.hebingFunction();
                    element.html("");
                    var table = $("<table class=\"table table-bordered\" style=\"margin-bottom:0px;\"></table>");
                    table.appendTo(element);
                    var thead = $("<thead></thead>");
                    thead.appendTo(table);
                    var trHead = $("<tr></tr>");
                    trHead.appendTo(thead);
                    //创建表头
                    $.each(scope.skuTitles, function (index, item) {
                        var td = $("<td>" + item + "</td>");
                        td.appendTo(trHead);
                    });
                    var itemColumHead = $("<td width=\"100\">价格（元）</td><td width=\"100\">库存</td> ");
                    itemColumHead.appendTo(trHead);
                    //var itemColumHead2 = $("<td >商家编码</td><td >商品条形码</td>");
                    //itemColumHead2.appendTo(trHead);
                    var tbody = $("<tbody></tbody>");
                    tbody.appendTo(table);
                    //生成组合
                    var zuheDate = scope.doExchange(scope.skuItems);
                    //过滤没有组合的SKU
                    if (zuheDate && zuheDate.length > 0) {
                        var sku_paths = [];
                        $.each(zuheDate, function (index, item) {
                            var item_sku_paths = [];
                            if (!$.isArray(item)) item_sku_paths.push(item.id);
                            else $.each(item, function (i, sku_value) {
                                item_sku_paths.push(sku_value.id);
                            });
                            sku_paths.push(item_sku_paths.join('-'));
                        });
                        scope.model.product_skus = $.grep(scope.model.product_skus, function (n, i) {
                            return $.inArray(n.sku_path, sku_paths) > -1;
                        });
                    } else scope.model.product_skus = [];
                    var colspan = 0;
                    if (zuheDate && zuheDate.length > 0) {
                        //创建行
                        $.each(zuheDate, function (index, item) {
                            var tr = $("<tr></tr>");
                            tr.appendTo(tbody);
                            var sku_paths = [];
                            var sku_names = [];
                            if (!$.isArray(item)) {
                                sku_paths.push(item.id);
                                sku_names.push(scope.skuTitles[index] + ':' + item.name);
                                var td = $("<td style=\"vertical-align: middle;\">" + item.name + "</td>");
                                td.appendTo(tr);
                                colspan++;
                            } else {
                                $.each(item, function (i, sku_value) {
                                    sku_paths.push(sku_value.id);
                                    sku_names.push(scope.skuTitles[i] + ':' + sku_value.name);
                                    var td = $("<td style=\"vertical-align: middle;\">" + sku_value.name + "</td>");
                                    td.appendTo(tr);
                                    colspan++;
                                });
                            }
                            var sku_path = sku_paths.join('-');
                            var sku_index = -1;
                            $.each(scope.model.product_skus, function (i, n) {
                                if (n.sku_path == sku_path) sku_index = i;
                                return sku_index;
                            });
                            var product_sku = {
                                id: 0,
                                sale_price: '',
                                stock: ''
                            };
                            if (sku_index == -1) {
                                product_sku.sku_path = sku_path;
                                product_sku.sku_name = sku_names.join(';');
                                scope.model.product_skus.push(product_sku);
                                sku_index = scope.model.product_skus.length - 1;
                            }
                            var td1 = $("<td><input name=\"product_skus[" + sku_index + "].sale_price\" class=\"form-control input-sm\" type=\"number\" ng-model=\"model.product_skus[" + sku_index + "].price\" w5c-dynamic-element required pattern=\"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$\"></td>");
                            td1.appendTo(tr);
                            var td2 = $("<td><input name=\"product_skus[" + sku_index + "].stock\" class=\"form-control input-sm\" type=\"number\" ng-model=\"model.product_skus[" + sku_index + "].stock\" ng-blur=\"set_stock()\" w5c-dynamic-element required pattern=\"^[0-9]+$\"></td>");
                            td2.appendTo(tr);
                            //var td3 = $("<td ><input name=\"Txt_NumberSon\" class=\"form-control input-sm\" type=\"text\" value=\"\"></td>");
                            //td3.appendTo(tr);
                            //var td4 = $("<td ><input name=\"Txt_SnSon\" class=\"form-control input-sm\" type=\"text\" value=\"\"></td>");
                            //td4.appendTo(tr);
                        });
                    }
                    var tfoot = $("<tfoot><tr><td colspan=\"" + (colspan + 2) + "\">批量设置： 价格    库存</td></tr></tfoot>");
                    tfoot.appendTo(table);
                    //结束创建Table表
                    //删除数组中最后一项
                    scope.skuColumn.pop();
                    //合并单元格
                    $(table).mergeCell({
                        cols: scope.skuColumn
                    });
                    //这个重要，可以双向绑定数据
                    $compile(element.contents())(scope);
                }
                //合并行
                scope.hebingFunction = function () {
                    $.fn.mergeCell = function (options) {
                        return this.each(function () {
                            var cols = options.cols;
                            for (var i = cols.length - 1; cols[i] != undefined; i--) {
                                // fixbug console调试 
                                // console.debug(cols[i]); 
                                mergeCell($(this), cols[i]);
                            }
                            dispose($(this));
                        });
                    };
                    // 如果对javascript的closure和scope概念比较清楚, 这是个插件内部使用的private方法            
                    function mergeCell($table, colIndex) {
                        $table.data('col-content', ''); // 存放单元格内容 
                        $table.data('col-rowspan', 1); // 存放计算的rowspan值 默认为1 
                        $table.data('col-td', $()); // 存放发现的第一个与前一行比较结果不同td(jQuery封装过的), 默认一个"空"的jquery对象 
                        $table.data('trNum', $('tbody tr', $table).length); // 要处理表格的总行数, 用于最后一行做特殊处理时进行判断之用 
                        // 我们对每一行数据进行"扫面"处理 关键是定位col-td, 和其对应的rowspan 
                        $('tbody tr', $table).each(function (index) {
                            // td:eq中的colIndex即列索引 
                            var $td = $('td:eq(' + colIndex + ')', this);
                            // 取出单元格的当前内容 
                            var currentContent = $td.html();
                            // 第一次时走此分支 
                            if ($table.data('col-content') == '') {
                                $table.data('col-content', currentContent);
                                $table.data('col-td', $td);
                            } else {
                                // 上一行与当前行内容相同 
                                if ($table.data('col-content') == currentContent) {
                                    // 上一行与当前行内容相同则col-rowspan累加, 保存新值 
                                    var rowspan = $table.data('col-rowspan') + 1;
                                    $table.data('col-rowspan', rowspan);
                                    // 值得注意的是 如果用了$td.remove()就会对其他列的处理造成影响 
                                    $td.hide();
                                    // 最后一行的情况比较特殊一点 
                                    // 比如最后2行 td中的内容是一样的, 那么到最后一行就应该把此时的col-td里保存的td设置rowspan 
                                    if (++index == $table.data('trNum')) $table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
                                } else { // 上一行与当前行内容不同 
                                    // col-rowspan默认为1, 如果统计出的col-rowspan没有变化, 不处理 
                                    if ($table.data('col-rowspan') != 1) {
                                        $table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
                                    }
                                    // 保存第一次出现不同内容的td, 和其内容, 重置col-rowspan 
                                    $table.data('col-td', $td);
                                    $table.data('col-content', $td.html());
                                    $table.data('col-rowspan', 1);
                                }
                            }
                        });
                    }
                    // 同样是个private函数 清理内存之用 
                    function dispose($table) {
                        $table.removeData();
                    }
                }
                //组合数组
                scope.doExchange = function (specValueList) {
                    var arrGroup = [],
                        tempGroup = [];
                    if (specValueList.length > 0) {
                        var firstSpecValueList = specValueList[0];
                        for (var i in firstSpecValueList) {
                            tempGroup.push([firstSpecValueList[i]]);
                        }
                        specValueList.splice(0, 1);
                        arrGroup = generateGroup(specValueList, tempGroup);
                    }
                    return arrGroup;
					/** 
					 * 生成规格值组合的方法 
					 */
                    function generateGroup(arrSpecValueList, tempGroup) {
                        for (var i in arrSpecValueList) {
                            var s = arrSpecValueList[i];
                            var newTempGroup = [];
                            for (var j in tempGroup) {
                                for (var k in s) {
                                    var tempOne = [];
                                    for (var x in tempGroup[j]) {
                                        tempOne.push(tempGroup[j][x]);
                                    }
                                    tempOne.push(s[k]);
                                    newTempGroup.push(tempOne);
                                }
                            }
                            if (newTempGroup.length > 0) {
                                tempGroup = newTempGroup;
                            }
                        }
                        return tempGroup;
                    }
                }
                scope.$on('sku:change', function () {
                    scope.creatTable();
                });
                scope.creatTable();
            }
        };
    });
});